import logging
from google.appengine.ext import webapp, db
from google.appengine.api import xmpp
from logger.api import Logger
from logger.models import LogSubscriber
from logger.settings import SETTINGS


class XMPPHandler(webapp.RequestHandler):

    def post(self):


        message_obj = xmpp.Message(self.request.POST)
        message = message_obj.body

        msg = ''
        cmd = 'log'

        if message.startswith('subscribe'):
            message = message[len('subscribe'):]
            cmd='subscribe'
        elif message.startswith('unsubscribe'):
            message = message[len('unsubscribe'):]
            cmd='unsubscribe'
        elif message.startswith('subscriptions'):
            message = message[len('subscriptions'):]
            cmd='subscriptions'
        elif message.startswith('log'):
            message = message[len('log'):]


        pairs = message.split(';')
        params = {}
        for pair in pairs:
            pair = pair.split('=')
            if len(pair)<>2:
                break
            pkey = pair[0].strip()
            pval = pair[1].strip()
            params[pkey] = pval

        domain = params.get('domain', None)
        context = params.get('context', None)
        eventtype = params.get('eventtype', params.get('event',None))


        if cmd == 'log' and (domain is None or \
                             context is None or \
                             eventtype is None):
            message_obj.reply('ERROR: domain, context and eventtype are '\
                          'required')
            return

        msg_key = params.get('key', None)
        msg_val = params.get('val', None)

        if cmd == 'log':
            l = Logger()
            l.log(domain, context, msg_key = msg_key,
                  msg_value = msg_val,
                  eventtype = eventtype)
            msg = 'logged d: %s c: %s e: %s k: %s v: %s' % (
                domain, context, eventtype, msg_key, msg_val)
            message_obj.reply(msg)
            return

        receiver_address = message_obj.sender
        if '/' in receiver_address:
            receiver_address = receiver_address.split('/')[0]

        if cmd == 'subscribe':

            s = LogSubscriber(domain=domain,
                              context=context,
                              eventtype=eventtype,
                              msg_key=msg_key,
                              receiver_type='xmpp',
                              receiver_address=receiver_address)
            s.put()

            message_obj.reply('subscription activated')
            return

        if cmd == 'subscriptions':
            sender = SETTINGS.get('jid_sender')

            q = LogSubscriber.all()
            q.filter('receiver_address =', receiver_address)
            items = q.fetch(50)
            msg = 'Your subscriptions: '

            for item in items:
                msg += '\nwant to \nunsubscribe key=%s;\n d: %s c: %s '\
                      'e: %s k: %s'  % (
                      item.key(), item.domain, item.context,
                      item.eventtype, item.msg_key)
            message_obj.reply(msg)
            return

        if cmd == 'unsubscribe':
            unsubscribe_key = params.get('key', None)
            if unsubscribe_key is None:
                message_obj.reply('ERROR: key not found')
                return

            db.delete(unsubscribe_key)
            message_obj.reply('successfully unsubscribed')
            return


